<?php

namespace plugin\ycMassage\app\model;

use plugin\ycMassage\utils\enum\MoneyAction;
use think\Exception;
use think\facade\Db;

class MassageUserAgentBill extends Model
{
    /**
     * 增加代理余额
     *
     * @param string $remarks 备注
     * @param integer $uid 代理用户ID
     * @param float|int|string $moeny 金额
     * @param integer|null $form_id 来源ID
     * @param boolean $thawing 是否解冻
     * @return void
     */
    public static function increase(string $remarks, int $uid, float|int|string $moeny, int $form_id = null, bool $thawing = false): void
    {
        $MassageUserWallet = MassageUserWallet::where(['uid' => $uid])->lock(true)->find();
        if (!$MassageUserWallet) {
            throw new Exception('用户钱包不存在');
        }
        $model = new self();
        $model->uid = $uid;
        $model->form_id = $form_id;
        $model->saas_appid = $MassageUserWallet->saas_appid;
        $model->money = $moeny;
        $model->old_money = $MassageUserWallet->agent_money;
        $model->new_money = $MassageUserWallet->agent_money + $moeny;
        $model->action = MoneyAction::INCREASE['value'];
        $model->remarks = $remarks;
        $model->save();

        $MassageUserWallet->agent_money = Db::raw('agent_money+' . $moeny);
        $MassageUserWallet->agent_money_sum = Db::raw('agent_money_sum+' . $moeny);
        if ($thawing) {
            $MassageUserWallet->agent_freeze_money = Db::raw('agent_freeze_money-' . $moeny);
        }
        $MassageUserWallet->save();
    }
    public static function decrease($remarks, $uid, $moeny, $form_id = null)
    {
        $MassageUserWallet = MassageUserWallet::where(['uid' => $uid])->lock(true)->find();
        if (!$MassageUserWallet) {
            throw new Exception('用户未开通钱包');
        }
        $moeny = abs($moeny);
        if ($MassageUserWallet->agent_money < $moeny) {
            throw new \Exception('余额不足');
        }
        $model = new self();
        $model->uid = $uid;
        $model->form_id = $form_id;
        $model->saas_appid = $MassageUserWallet->saas_appid;
        $model->money = $moeny;
        $model->old_money = $MassageUserWallet->agent_money;
        $model->new_money = $MassageUserWallet->agent_money - $moeny;
        $model->action = MoneyAction::DECREASE['value'];
        $model->remarks = $remarks;
        $model->save();

        $MassageUserWallet->agent_money = Db::raw('agent_money-' . $moeny);
        $MassageUserWallet->save();
    }
}
